/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ThreadsScreen.java
 *
 * Created on Apr 18, 2011, 3:46:07 PM
 */

package forumGUI;

import client.ForumClientListener;
import client.TcpClient;
import forum.Post;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import messaage.*;

/**
 *
 * @author Olga
 */
public class ThreadsScreen extends javax.swing.JFrame implements client.MessagesListener {
    private TcpClient client;
    private String username;
    private boolean isModerator;
    private int forumID;
    private String forumSubject;
    private ArrayList<forum.Thread> threadsLogic;
    private ArrayList<ArrayList<Post>> postsLogic;
    private DefaultListModel threadsListModel;
    private DefaultListModel postsListModel;


    
    /** Creates new form ThreadsScreen */
    public ThreadsScreen(TcpClient _client, String _username,
			boolean _isModerator, int _forumID, String _forumSubject) {
        initComponents();
        this.setBackground();

        this.client = _client;
        this.username = _username;
        this.isModerator = _isModerator;
        this.forumID = _forumID;
        this.forumSubject = _forumSubject;
        this.postContentField.setEditable(false);

        this.threadsListModel = new DefaultListModel();
        this.threadsList.setModel(this.threadsListModel);

        this.postsListModel = new DefaultListModel();
        this.postsList.setModel(this.postsListModel);

        this.threadsLogic = new ArrayList<forum.Thread>();
        this.postsLogic = new ArrayList<ArrayList<Post>>();
        
        this.postContentField.setLineWrap(true);
        this.postContentField.setWrapStyleWord(true);

    }

    public void setBackground()
    {
        Container con =this.getContentPane();
        JPanel panelBgImg;
        con.setLayout(null);
        final String photoPath = "src/images/screen.jpg";
        ImageIcon imh = new ImageIcon(photoPath);
//        setSize(imh.getIconWidth(), imh.getIconHeight());

        panelBgImg = new JPanel()
        {
            @Override
            public void paintComponent(Graphics g)
            {
                Image img = new ImageIcon(photoPath).getImage();

                Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                setPreferredSize(size);
                setMinimumSize(size);
                setMaximumSize(size);
                setSize(size);
                setLayout(null);
                g.drawImage(img, 0, 0, null);
            }
        };

        con.add(panelBgImg);
        panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());

    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        postContentLabel = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        postContentField = new javax.swing.JTextArea();
        addTopicButton = new javax.swing.JButton();
        addReplyButton = new javax.swing.JButton();
        editPostButton = new javax.swing.JButton();
        BackToForumsButton = new javax.swing.JButton();
        logoutButton = new javax.swing.JButton();
        removePost = new javax.swing.JButton();
        friendsButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        threadsList = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        postsList = new javax.swing.JList();
        threadsLabel = new javax.swing.JLabel();
        PostsLabel = new javax.swing.JLabel();
        resetButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        postContentLabel.setText("Post content:");

        postContentField.setColumns(20);
        postContentField.setEditable(false);
        postContentField.setRows(5);
        jScrollPane2.setViewportView(postContentField);

        addTopicButton.setText("add topic");
        addTopicButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addTopicButtonActionPerformed(evt);
            }
        });

        addReplyButton.setText("add reply");
        addReplyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addReplyButtonActionPerformed(evt);
            }
        });

        editPostButton.setText("edit post");
        editPostButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editPostButtonActionPerformed(evt);
            }
        });

        BackToForumsButton.setText("back to forums");
        BackToForumsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BackToForumsButtonActionPerformed(evt);
            }
        });

        logoutButton.setText("logout");
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutButtonActionPerformed(evt);
            }
        });

        removePost.setText("remove post");
        removePost.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removePostActionPerformed(evt);
            }
        });

        friendsButton.setText("friends list");
        friendsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                friendsButtonActionPerformed(evt);
            }
        });

        threadsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                threadsListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(threadsList);

        postsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                postsListValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(postsList);

        threadsLabel.setText("Threads:");

        PostsLabel.setText("Posts:");

        resetButton.setText("Reset");
        resetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addReplyButton)
                    .addComponent(addTopicButton)
                    .addComponent(threadsLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(PostsLabel)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(editPostButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(removePost, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(postContentLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(friendsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(BackToForumsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 503, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(resetButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(logoutButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 669, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(postContentLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(threadsLabel)
                    .addComponent(PostsLabel))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addTopicButton)
                    .addComponent(editPostButton)
                    .addComponent(BackToForumsButton)
                    .addComponent(logoutButton))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addReplyButton)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(removePost)
                        .addComponent(friendsButton)
                        .addComponent(resetButton)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BackToForumsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackToForumsButtonActionPerformed
            // create new forums screen
		forumsScreen fs = new forumsScreen(this.client, this.username, this.isModerator);
            // sets new frame as listener
		ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
		tempListener.getConnector().addListener(fs);
            // create getList of forums msg
		GetListOfForumsMsg listMsg = new GetListOfForumsMsg(this.username);
		this.client.sendMessage(listMsg);
            // remove this frame from socket liseners
		tempListener.getConnector().removeListener(this);
		this.setVisible(false);
    }//GEN-LAST:event_BackToForumsButtonActionPerformed

    private void addTopicButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addTopicButtonActionPerformed
        	addThreadScreen ats = new addThreadScreen(client, username, this,
				this.forumID);
		ats.setVisible(true);
		this.setEnabled(false);
    }//GEN-LAST:event_addTopicButtonActionPerformed

    private void addReplyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addReplyButtonActionPerformed

         int threadIndex = this.threadsList.getSelectedIndex();
         if (threadIndex < 0){
              JOptionPane.showMessageDialog(this, "Please select the post!!!");
              return;
        }
          Post postToReply = this.threadsLogic.get(threadIndex).getRoot();
          //create add post screen
          addPostScreen aps = new addPostScreen(this.client, this.username, this, postToReply.getID(), this.forumID);
	  aps.setVisible(true);
	  this.setEnabled(false);
    }//GEN-LAST:event_addReplyButtonActionPerformed

    private void editPostButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editPostButtonActionPerformed

        //if post selected -> edit post
        //else check if thread is selected -> edit thread
        //else errorMsg
         int postIndex = this.postsList.getSelectedIndex();
         int threadIndex = this.threadsList.getSelectedIndex();
         Post postToEdit;
         if (postIndex >= 0 && threadIndex >= 0)
             postToEdit = this.postsLogic.get(threadIndex).get(postIndex);
         else
             if (threadIndex >= 0)
                 postToEdit = this.threadsLogic.get(threadIndex).getRoot();
             else{
              JOptionPane.showMessageDialog(this, "Please select the post!!!");
              return;
             }

         editPostScreen eps = new editPostScreen(this.client, this.username,
                        this, postToEdit, this.forumID);
        eps.setVisible(true);
        this.setEnabled(false);
    }//GEN-LAST:event_editPostButtonActionPerformed

    private void removePostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removePostActionPerformed
	//if post selected -> remove post
        //else check if thread is selected -> remove thread
        //else errorMsg
         int postIndex = this.postsList.getSelectedIndex();
         int threadIndex = this.threadsList.getSelectedIndex();
         Post postToRemove;
         if (postIndex >= 0 && threadIndex >= 0){
             postToRemove = this.postsLogic.get(threadIndex).get(postIndex);
             this.client.sendMessage(new RemovePostMsg(this.username, this.forumID+"", postToRemove.getID()+""));
         }
         else
             if (threadIndex >= 0){
                 postToRemove = this.threadsLogic.get(threadIndex).getRoot();
                 this.client.sendMessage(new RemoveThreadMsg(this.username, this.forumID+"", postToRemove.getID()+""));
             }
             else{
              JOptionPane.showMessageDialog(this, "Please select the post!!!");
              return;
             }
         
    }//GEN-LAST:event_removePostActionPerformed

    private void friendsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_friendsButtonActionPerformed
        // create new friendsScreen
        friendsScreen fs = new friendsScreen(this.client, this.username,
                        this.isModerator);
        // adds new listener to socket
        ((ForumClientListener) this.client.getListener()).getConnector()
                        .addListener(fs);
        // send getFriens msg
        this.client.sendMessage(new GetFriendsListMsg(this.username));
        ForumClientListener tempListener = (ForumClientListener) this.client
                        .getListener();
        tempListener.getConnector().removeListener(this);
        this.setVisible(false);
    }//GEN-LAST:event_friendsButtonActionPerformed

    private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoutButtonActionPerformed
        LogoutMsg msg = new LogoutMsg(username);
	this.client.sendMessage(msg);
    }//GEN-LAST:event_logoutButtonActionPerformed

    private void threadsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_threadsListValueChanged

		if (evt.getValueIsAdjusting()) {
			int threadIndex = this.threadsList.getSelectedIndex();
			forum.Thread thread = this.threadsLogic.get(threadIndex);
			this.postsList.clearSelection();
			String content = thread.getRoot().getAuthor() + " posted at "
					+ thread.getRoot().getDate() + "\n";
			content += "Subject: " + thread.getRoot().getSubject() + "\n";
			content += "Content:\n\t" + thread.getRoot().getContent();
			this.postContentField.setText(content);
			this.client.sendMessage(new GetThreadMsg(this.username,
					this.forumID + "", thread.getRoot().getID() + ""));
		}
    }//GEN-LAST:event_threadsListValueChanged

    private void postsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_postsListValueChanged
        
		if (evt.getValueIsAdjusting()) {
			int threadIndex = this.threadsList.getSelectedIndex();
			int postIndex = this.postsList.getSelectedIndex();
			if (threadIndex >= 0 && postIndex >= 0) {
				Post post = this.postsLogic.get(threadIndex).get(postIndex);
				String content = post.getAuthor() + " posted at " + post.getDate() + "\n";
				content += "Subject: " + post.getSubject() + "\n";
				content += "Content:\n\t" + post.getContent();
				this.postContentField.setText(content);
			} else
				 JOptionPane.showMessageDialog(this, "Please select the thread!");
			
		}
    }//GEN-LAST:event_postsListValueChanged

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
       this.threadsList.clearSelection();
       this.postsList.clearSelection();
       this.postContentField.setText("");
    }//GEN-LAST:event_resetButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                //new ThreadsScreen().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BackToForumsButton;
    private javax.swing.JLabel PostsLabel;
    private javax.swing.JButton addReplyButton;
    private javax.swing.JButton addTopicButton;
    private javax.swing.JButton editPostButton;
    private javax.swing.JButton friendsButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton logoutButton;
    private javax.swing.JTextArea postContentField;
    private javax.swing.JLabel postContentLabel;
    private javax.swing.JList postsList;
    private javax.swing.JButton removePost;
    private javax.swing.JButton resetButton;
    private javax.swing.JLabel threadsLabel;
    private javax.swing.JList threadsList;
    // End of variables declaration//GEN-END:variables

   @Override
	public void connected(ConnectedMsg msg) {
	}

	@Override
	public void disconnected(DisconnectedMsg msg) {
	}

	@Override
	public void errorMessage(ErrorMsg msg) {
		String body = msg.getBody();
		JOptionPane.showMessageDialog(this, body);
	}

	@Override
	public void registered(RegisteredMsg msg) {
	}

	@Override
	public void loggedIn(LoggedInMsg msg) {
	}

	@Override
	public void loggedOff(LoggedOffMsg msg) {
		ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
        tempListener.getConnector().removeListener(this);
		this.setVisible(false);
		MainScreen ms = new MainScreen(client);
		tempListener.getConnector().addListener(ms);
		ms.setVisible(true);
	}

	@Override
	public void gotListOfForums(GotListOfForumsMsg msg) {
	}

	@Override
	public void gotTopicsOfForum(GotTopicsOfForumMsg msg) {
            //clear all
            this.threadsLogic = new ArrayList<forum.Thread>();
            this.postsLogic = new ArrayList<ArrayList<Post>>();
            this.threadsListModel = new DefaultListModel();
            this.postsListModel = new DefaultListModel();
            //init all
            if (msg.getForumID() == this.forumID) {
                    for (forum.Thread t : msg.getListOfTopics()) {
                            this.threadsLogic.add(t);
                            this.postsLogic.add(new ArrayList<Post>());
                            this.threadsListModel.addElement(t.getRoot().getSubject());
                    }
            }
            this.threadsList.setModel(threadsListModel);
            this.postsList.setModel(postsListModel);
            this.setVisible(true);
	}

	/**
	 * @param msg
	 */
	@Override
	public void gotThread(GotThreadMsg msg) {
		this.postsListModel = new DefaultListModel();
		int threadID = msg.getThread().getRoot().getID();
		int threadIndex = findIndexOfThread(threadID);
		if (threadIndex < 0) {
			System.out.println("ERROR IN GOT_THREAD!!! THREAD WITH ID "
					+ threadID + " NOT FOUND");
			return;
		}
		List<Post> poststToAdd = msg.getThread().getRoot().getReplies();
		this.postsListModel = new DefaultListModel();
		this.postsLogic.get(threadIndex).clear();
		for (int i = 0; i < poststToAdd.size(); i++) {
			Post p = poststToAdd.get(i);
			this.postsLogic.get(threadIndex).add(p);
			this.postsListModel.addElement(p.getSubject());
		}
		this.postsList.setModel(postsListModel);
	}

	private int findIndexOfThread(int threadID) {
		for (int i = 0; i < this.threadsLogic.size(); i++) {
			if (this.threadsLogic.get(i).getRoot().getID() == threadID)
				return i;
		}
		return -1;
	}

	@Override
	public synchronized void addedPost(AddedPostMsg msg) {
		int threadID = Integer.parseInt(msg.getParentID());
		int threadIndex = findIndexOfThread(threadID);
		
		if (threadIndex < 0) {
			System.out.println("ERROR IN addedPost!!! THREAD WITH ID "
					+ threadID + " NOT FOUND");
			return;
		}	
		String author = msg.getAuthor();
		String content = msg.getContent();
		String date = msg.getDate();
		String subject = msg.getSubject();
		int postID = Integer.parseInt(msg.getPostID());
		this.postsLogic.get(threadIndex).add(new Post(postID, subject, content, null, date, author));
		// post added only to selected thread
		if (this.threadsList.getSelectedIndex() >= 0 && threadID == this.threadsLogic.get(this.threadsList.getSelectedIndex()).getID())
			this.postsListModel.addElement(subject);
	}

	@Override
	public void createdThread(CreatedThreadMsg msg) {
		if (msg.getForumID() == this.forumID) {
			this.threadsLogic.add(msg.getThread());
			this.postsLogic.add(new ArrayList<Post>());
			this.threadsListModel.addElement(msg.getThread().getRoot().getSubject());
		}
	}

	@Override
	public void addedForum(AddedForumMsg msg) {
	}

	@Override
	public void removedForum(RemovedForumMsg msg) {
		if (msg.getForumID() == this.forumID) {
			JOptionPane
					.showMessageDialog(
							this,
							"Sorry, but this forum was just removed.\nYou will be redirected to forums list :(");
			forumsScreen fs = new forumsScreen(this.client, this.username,
					this.isModerator);
			ForumClientListener tempListener = (ForumClientListener) this.client
					.getListener();
			tempListener.getConnector().addListener(fs);
			GetListOfForumsMsg listMsg = new GetListOfForumsMsg(this.username);
			this.client.sendMessage(listMsg);
			tempListener.getConnector().removeListener(this);
			this.setVisible(false);
		}
	}
	
	private Post findPost(int postID){		
		for (int i = 0; i < this.postsLogic.size(); i++){
			List<Post> l = this.postsLogic.get(i);
			for (Post p : l)
				if (p.getID() == postID)
					return p;
		}
		return null;
	}

	@Override
	public void editedPost(EditedPostMsg msg) {

		int postID = Integer.parseInt(msg.getPostID());
		Post p = this.findPost(postID);
		if (p == null){
			System.out.println("ERROR IN editedPost!!! post WITH ID "
					+ postID + " NOT FOUND");
			return;
		}
		p.setContent(msg.getNewContent());
		p.setDate(msg.getDate());
		// if post is selected, update the view
		int selectedThread = this.threadsList.getSelectedIndex();
		int selectedPost = this.postsList.getSelectedIndex();
		
		if (selectedThread >= 0
				&& selectedPost >= 0
				&& this.postsLogic.get(selectedThread).get(selectedPost).getID() == postID) {
			
			String content = p.getAuthor() + " posted at " + p.getDate() + "\n";
			content += "Subject: " + p.getSubject() + "\n";
			content += "Content:\n\t" + p.getContent();
			
			this.postContentField.setText(content);

		}
	}

	@Override
	public void removedUser(RemovedUserMsg msg) {
		if (msg.getUsernameToRemove().equalsIgnoreCase(this.username)) {
			JOptionPane.showMessageDialog(this,
					"Sorry, but you was just removed from the forum :(");
	        ForumClientListener tempListener = (ForumClientListener) this.client.getListener();
	        tempListener.getConnector().removeListener(this);
			this.setVisible(false);
		}
	}

	@Override
	public void removedThread(RemovedThreadMsg msg) {
		int threadID = msg.getThreadID();
		int index = this.findIndexOfThread(threadID);
		this.threadsLogic.remove(index);
		this.threadsListModel.removeElementAt(index);
		this.postsLogic.remove(index);
		this.postContentField.setText("");
	}

	private int findThreadIndexOfPost(int postID){
		for (int i = 0; i < this.postsLogic.size(); i++){
			List<Post> l = this.postsLogic.get(i);
			for (int j = 0; j < l.size(); j++)
				if (l.get(j).getID() == postID)
					return i;
		}
		return -1;
	}
	
	@Override
	public void removedPost(RemovedPostMsg msg) {
		int postID = msg.getPostID();
		int threadIndex = findThreadIndexOfPost(postID);
		Post p = findPost(postID);
		
		//remove from GUI
		int selectedThread = this.threadsList.getSelectedIndex();
		int selectedPost = this.postsList.getSelectedIndex();
		
		if (selectedThread >= 0
				&& selectedPost >= 0
				&& this.postsLogic.get(selectedThread).get(selectedPost).getID() == postID) {
			this.postsListModel.remove(selectedPost);
			this.postContentField.setText("");
		}
		
		//remove from logic
		if (threadIndex < 0 || p == null){
			System.out.println("ERROR IN removedPost!!! post WITH ID "
					+ postID + " NOT FOUND in threads");
			return;
		}
		this.postsLogic.get(threadIndex).remove(p);
				
	}

	@Override
	public void addedFriend(AddedFriendMsg msg) {
	}

	@Override
	public void removedFriend(RemovedFriendMsg msg) {
	}

	@Override
	public void gotFriendsList(GotFriendsListMsg msg) {
	}

	@Override
	public void friendNotifyMsgReceived(FriendNotifyMsg msg) {
		String body = "Your Friend added a new post to the forum!";
		JOptionPane.showMessageDialog(this, body);
	}

	@Override
	public void viewerNotifyMsgReceived(ViewerNotifyMsg msg) {
		
		int threadIndex = this.threadsList.getSelectedIndex();
		forum.Thread thread = this.threadsLogic.get(threadIndex);
		this.postsList.clearSelection();
		String content = thread.getRoot().getAuthor() + " posted at "
				+ thread.getRoot().getDate() + "\n";
		content += "Subject: " + thread.getRoot().getSubject() + "\n";
		content += "Content:\n\t" + thread.getRoot().getContent();
		this.postContentField.setText(content);		
		this.client.sendMessage(new GetThreadMsg(this.username,	this.forumID + "", thread.getRoot().getID() + ""));		
	}
	
	@Override
	public void authorNotifyMsgReceived(AuthorNotifyMsg msg) {
		String body = "Post was added to your thread";
		JOptionPane.showMessageDialog(this, body);
	}

}
